package com.killer.service;

import com.killer.dao.SeckillMapper;
import com.killer.pojo.Seckill;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class SeckillService {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Autowired
    public SeckillMapper seckillMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增秒杀活动
     * @param productId
     * @param count
     */
    public Seckill addSeckill(Long productId, Integer count) {
        Seckill seckill=new Seckill();
        seckill.setProductId(productId);
        seckill.setCount(count);
        //保存到数据库
        seckillMapper.insert(seckill);
        //同时保存到redis，用于抗高并发
        redisTemplate.opsForValue().set("seckill_"+seckill.getId(), seckill.getCount().toString());
        return seckill;
    }

    /**
     * 执行秒杀
     * @param seckillId
     */
    public void doSeckill(Long seckillId) {
        Boolean result = redisTemplate.opsForValue().setIfAbsent("seckill_lock_" + seckillId, "1", 30, TimeUnit.SECONDS);
        if (result) {
            System.out.println(Thread.currentThread()+"获取到分布式锁,准备执行秒杀操作");

            try {
                //获取库存数
                String value=redisTemplate.opsForValue().get("seckill_"  +seckillId).toString();
                Integer count = Integer.parseInt(value);
                if (count <= 0) {
                    throw new RuntimeException("当前商品库存不足");
                }
                //库存减1
                redisTemplate.opsForValue().decrement("seckill_"  +seckillId);
                //扣减库存
                rocketMQTemplate.syncSend("seckill", seckillId);
                //生成订单
                rocketMQTemplate.syncSend("order",seckillId);
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                System.out.println(Thread.currentThread()+"释放分布式锁");
                //业务完成,释放锁
                redisTemplate.delete("seckill_lock_" + seckillId);
            }
        }else{
            System.out.println(Thread.currentThread()+"没有获取到分布式锁,无法进行秒杀");
        }

    }

    public void recoverStorage(Long seckillId) {
        seckillMapper.recoverStorage(seckillId);
    }

    public void minusStorage(Long seckillId) {
        seckillMapper.minusStorage(seckillId);
    }

    /**
     * 根据秒杀id查询秒杀活动
     *
     * @param seckillId
     * @return
     */
    public Seckill findById(Long seckillId) {
        return seckillMapper.selectById(seckillId);
    }
}
